package com.springcloud.movieservice.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import com.springcloud.movieservice.clients.AuthorServiceClient;
import com.springcloud.movieservice.config.PatternConfig;
import com.springcloud.movieservice.pojo.Author;
import com.springcloud.movieservice.pojo.Movie;
import com.springcloud.movieservice.pojo.MovieInfo;
import com.springcloud.movieservice.service.MovieService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/movie")
public class MovieController {
    @Autowired
    private MovieService movieService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private PatternConfig patternConfig;
    @Autowired
    private AuthorServiceClient authorServiceClient;
    @Value("${author.url}")
    private String authorUrl;
    @GetMapping("/{id}")
    /*@HystrixCommand(
            fallbackMethod = "getMovieByIdFallback",
            commandProperties = {
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true"),
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD , value = "6"),
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE , value = "50"),
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS , value = "3000")
            }
    )*/
    public MovieInfo getMovieById(@PathVariable Integer id){
        Movie movie= movieService.getMovieById(id);
//        Author author=restTemplate.getForObject(authorUrl+movie.getAuthor_id(),Author.class);
        Author author = authorServiceClient.getById(id);
        return setAuthorToMovie(movie,author);
    }
    /*public MovieInfo getMovieByIdFallback(@PathVariable Integer id){
        MovieInfo movieInfo = new MovieInfo();
        movieInfo.setName("服务异常！！！");
        return movieInfo;
    }*/
    private MovieInfo setAuthorToMovie(Movie movie,Author author){
        MovieInfo movieInfo=new MovieInfo();
        BeanUtils.copyProperties(movie,movieInfo);
        movieInfo.setAuthor(author);
        System.out.println("=========="+patternConfig);
        return movieInfo;
    }
}
